<?php

namespace app\admin\controller\cms;

use app\admin\model\cms\ChartTableModel;
use app\common\controller\Backend;
use Cassandra\DefaultTable;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use app\common\model\ChartParent;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 自定义表单表
 *
 * @icon fa fa-list
 */
class Diyform extends Backend
{

    /**
     * Model模型对象
     */
    protected $model = null;
    protected $searchFields = 'id,name,title,table';
    protected $noNeedRight = ['check_element_available'];

    public function _initialize()
    {
        parent::_initialize();
        $config = get_addon_config('cms');
        $config = ['diyformdatalimit'=> "all",'spiderrecord'=>0];
        if ($config['diyformdatalimit'] != 'all') {
            $this->dataLimit = $config['diyformdatalimit'];
        }
        $chart_parent = collection(ChartParent::order('id desc')->select())->toArray();
        $this->assignconfig('spiderRecord', intval($config['spiderrecord']?? 0));
        $chart_parentdata = [];
        foreach($chart_parent as $k => $v)
        {
            $chart_parentdata[$v['id']] = $v;
        }
        $max = Db::table('fa_pro_fields')->where('1=1')->order('source_id desc')->find();
        $maxid = !empty($max) ?$max['source_id']+1:1;
        $this->model = new \app\admin\model\cms\Diyform;
        $this->view->assign("chart_id", $maxid);
        $this->view->assign("parentList", $chart_parentdata);
        $this->view->assign("statusList", $this->model->getStatusList());

        $fieldsList = ChartTableModel::FieldName;
        $this->view->assign("fieldsList", $fieldsList);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);


//            \app\admin\model\cms\SpiderLog::render($list, 'diyform');

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    //加载上传文件页面
    public function uploadfile()
    {
        return $this->view->fetch();
    }

    //接收上传的Exexle文件
    public function import()
    {
        header("content-type:text/html;charset=utf-8");
        $file = request()->file('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel');
        if ($info) {
            $fileName = $info->getSaveName();
            $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel' . DS . $fileName;
            if (!is_file($filePath)) {
                $this->error(__('No results were found') . $fileName);
            }

        }

        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format') . $ext);
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $table = $this->model->getQuery()->getTable();
//        $form_id = $this->request->request('form_id');
        $table = 'chart_table';
        $table = empty($table) ? '' : 'fa_' . $table;
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
//       var_dump(\think\Db::getLastSql());exit;
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];

        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields_zh = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields_zh[] = $val;//execle中的字段名
                }
            }

            $field_name_list = ChartTableModel::FieldName;
            $field_name_list = array_merge($field_name_list,['datetime'=>'日期']);
            $fields = [];
            foreach($fields_zh as $v){
                $fields[] = array_search($v,$field_name_list);
            }
            $j = 1;

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $date = $PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue();
                if (is_null($date)) {
                    break;
                }
                $date = date('Y-m-d', Date::excelToTimestamp($date));
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;

                }
                $row = [];
                $arLen = count($fields);

                for ($i = count($values); $i < $arLen; $i++) {
                    $values[$i] = 0;
                }
                $temp = array_combine($fields, $values);

                $temp['createtime'] = time();
                $temp['updatetime'] = time();
                $temp['datetime'] = $date;
                //更具日期查询数据是否存在,存在就更新,否则就新增
                $chartTableModel = ChartTableModel::where('datetime',$temp['datetime'])
                    ->find();
                if ($chartTableModel){
                    $update_data = $temp;
                    unset($update_data['createtime'],$update_data['datetime']);
                    foreach($update_data as $k=>$v){
                        if (!$v){
                            unset($update_data[$k]);
                        }
                    }
                    $last_id = ChartTableModel::where('id',$chartTableModel['id'])->update($update_data);
                }else{

                    $last_id = ChartTableModel::insertGetId($temp);
                }
//                 if ($last_id) {
//                    echo "第".$j."行导入成功，users表第:".$last_id."条！<br/>";
//                }else{
//                    echo "第".$j."行导入失败！<br/>";
//                }
                if ($last_id) {
                    $j++;
                }
//                foreach ($temp as $k => $v) {
//                    if (isset($fieldArr[$k]) && $k !== '') {
//                        $row[$fieldArr[$k]] = $v;
//                    }
//                }
//                if ($row) {
//                    $insert[] = $temp;
//                }
            }
            if ($j > 0) {
                $this->success('导入成功');
            } else {
                $this->error('导入失败,请检查是否有重复或者模板格式是否正确！');
            }
//            $this->success('导入成功');
            exit;
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
//        print_r($insert);exit;
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
//            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    //接收上传的Exexle文件-旧版本,已经废弃
    public function import_OLD()
    {
        header("content-type:text/html;charset=utf-8");
        $file = request()->file('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel');
        if ($info) {
            $fileName = $info->getSaveName();
            $filePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel' . DS . $fileName;
            if (!is_file($filePath)) {
                $this->error(__('No results were found') . $fileName);
            }

        }

        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format') . $ext);
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $table = $this->model->getQuery()->getTable();
        $form_id = $this->request->request('form_id');
        $table = $this->model->where('id', $form_id)->value('table');
        $table = empty($table) ? '' : 'fa_' . $table;
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
//       var_dump(\think\Db::getLastSql());exit;
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            $j = 1;
//            $fields = ['datetime','income_yield','enhance_yield'];
            $fields = ['datetime', 'field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7', 'field8', 'field9', 'field10', 'field11', 'field12', 'field13', 'field14', 'field15', 'field16', 'field17', 'field18', 'field19', 'field20', 'field21', 'field22', 'field23', 'field24', 'field25', 'field26', 'field27', 'field28'];

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $date = $PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue();
                if (is_null($date)) {
                    break;
//                        echo $date;exit;
                }
                $date = date('Y-m-d', Date::excelToTimestamp($date));
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;

                }
                $row = [];
                $arLen = count($fields);
                for ($i = count($values); $i < $arLen; $i++) {
                    $values[$i] = 0;
                }
                $temp = array_combine($fields, $values);

                $temp['createtime'] = time();
                $temp['updatetime'] = time();
                $temp['datetime'] = $date;
                $last_id = Db::table($table)->insertGetId($temp);
//                 if ($last_id) {
//                    echo "第".$j."行导入成功，users表第:".$last_id."条！<br/>";
//                }else{
//                    echo "第".$j."行导入失败！<br/>";
//                }
                if ($last_id) {
                    $j++;
                }
//                foreach ($temp as $k => $v) {
//                    if (isset($fieldArr[$k]) && $k !== '') {
//                        $row[$fieldArr[$k]] = $v;
//                    }
//                }
//                if ($row) {
//                    $insert[] = $temp;
//                }
            }
            if ($j > 0) {
                $this->success('导入成功');
            } else {
                $this->error('导入失败,请检查是否有重复或者模板格式是否正确！');
            }
//            $this->success('导入成功');
            exit;
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
//        print_r($insert);exit;
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
//            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    public function importExcel()
    {
        header("content-type:text/html;charset=utf-8");
        //引入PHPExcel类
        vendor('PHPExcel');
        vendor('PHPExcel.IOFactory');
        vendor('PHPExcel.Reader.Excel5');
        //redirect传来的文件名
        $fileName = $_GET['fileName'];
        //文件路径

        $filePath = './Home/temp/' . $fileName . '.xlsx';
        //实例化PHPExcel类
        $PHPExcel = new PHPExcel();

        //默认用excel2007读取excel，若格式不对，则用之前的版本进行读取

        $PHPReader = new PHPExcel_Reader_Excel2007();

        if (!$PHPReader->canRead($filePath)) {

            $PHPReader = new PHPExcel_Reader_Excel5();

            if (!$PHPReader->canRead($filePath)) {

                echo 'no Excel';

                return;

            }

        }


        //读取Excel文件

        $PHPExcel = $PHPReader->load($filePath);

        //读取excel文件中的第一个工作表

        $sheet = $PHPExcel->getSheet(0);

        //取得最大的列号

        $allColumn = $sheet->getHighestColumn();

        //取得最大的行号

        $allRow = $sheet->getHighestRow();

        //从第二行开始插入,第一行是列名

        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {

            //获取B列的值

            $name = $PHPExcel->getActiveSheet()->getCell("B" . $currentRow)->getValue();

            //获取C列的值

            $price = $PHPExcel->getActiveSheet()->getCell("C" . $currentRow)->getValue();

            //获取D列的值

            $count = $PHPExcel->getActiveSheet()->getCell("D" . $currentRow)->getValue();


            $m = M('Info');

            $num = $m->add(array('pName' => $name, 'pPrice' => $price, 'pCount' => $count));

        }

        if ($num > 0) {

            echo "添加成功！";

        } else {

            echo "添加失败！";

        }

    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }


        $fieldsList = ChartTableModel::FieldName;
        $fields = [];
        foreach ($fieldsList as $k => $v) {
            if ($params[$k] ?? null) {
                if ($params[$k . '_as'] ?? null) {
                    $fields[] = [
                        $k => $params[$k . '_as']
                    ];
                }
            }
        }

        if ($fields) {
            $params['fields'] = json_encode($fields, true);
        } else {
            $this->error('请选择并填写"字段列表"');
        }

        $params['table'] = 'chart_table';//把table字段强制改为'chart_table',不然数据坐标表查不到值

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $fieldsList = ChartTableModel::FieldName;
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            //处理fields字段选中项目
            $fields = [];
            foreach ($row['fields'] as $v){
                $fields = array_merge($fields,json_decode(trim($v,'[]'),true));
            }

            foreach ($fieldsList as $k=>$v){
                $fieldsEditList[] = [
                    'key' => $k,
                    'name' => $v,
                    'as_name' => $fields[$k] ?? null
                ];
            }
            $this->view->assign('fieldsEditList', $fieldsEditList);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        //处理提交过来的fields字段
        $fieldsList = ChartTableModel::FieldName;
        $fields = [];
        foreach($fieldsList as $k=>$v){
            if ($params[$k] ?? null){
                if ($params[$k . '_as']  ?? null){
                    $fields[] = [
                        $k=>$params[$k . '_as']
                    ];
                }
            }
        }

        if ($fields){
            $params['fields'] = json_encode($fields,true);
        }else{
            $this->error('请选择并填写"字段列表"');
        }

        $params['table'] = 'chart_table';//把table字段强制改为'chart_table',不然数据坐标表查不到值

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 检测元素是否可用
     * @internal
     */
    public function check_element_available()
    {
        $id = $this->request->request('id');
        $name = $this->request->request('name');
        $value = $this->request->request('value');
        $name = substr($name, 4, -1);
        if (!$name) {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        if ($id) {
            $this->model->where('id', '<>', $id);
        }
        $exist = $this->model->where($name, $value)->find();
        if ($exist) {
            $this->error(__('The data already exist'));
        } else {
            $this->success();
        }
    }
}
